package com.example.administrator.my_musicplayer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.administrator.my_musicplayer.R.id.listview1;

public class MainActivity extends AppCompatActivity {

    private ImageButton imgBtn_Prev;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Next;
    private ImageButton repeat;
    private ListView list;
//    private ArrayList<Music> musicArrayList = new ArrayList<>();

    private LinearLayout root_Layout;
    private int status;
    String[] media_music_info = new String[]{MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.DISPLAY_NAME};

    private int number = 0;
    private StatusChangedReceiver receiver;

    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private Handler seekBarHandler;


    private int duration = 0;
    private int time = 0;



    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;



    private static final int MODE_LIST_SEQUENCE =0;
    private static final int MODE_SINGLE_CYCLE =1;
    private static final int MODE_LIST_CYCLE =2;
    private int playmode;


    //睡眠模式相关组件，标识常量
    private ImageView iv_sleep;
    private Timer timer_sleep;
    private static final boolean NOTSLEEP= false;
    private static final boolean ISSLEEP =true;
    //默认睡眠时间
    private int sleepminute =20;
    //标记是否打开睡眠模式
    private static  boolean sleepmode;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findId();
        setLitenser();
        initmusiclist();
        initListView();
        checkMusicfile();

        initSeekBarHandler();

        bindStatusChangedReceiver();
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;

        playmode = MainActivity.MODE_LIST_SEQUENCE;
        sleepmode = MainActivity.NOTSLEEP;
    }

    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }


    private void findId() {
        imgBtn_Prev = (ImageButton) findViewById(R.id.imageButton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imageButton2);
        imgBtn_Next = (ImageButton) findViewById(R.id.imageButton3);
        repeat = (ImageButton) findViewById(R.id.imageButton_repeat);
        list = (ListView) findViewById(R.id.listview1);

        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        text_Current = (TextView) findViewById(R.id.textView1);
        text_Duration = (TextView) findViewById(R.id.textView2);
        root_Layout = (LinearLayout) findViewById(R.id.relativeLayout1);
        iv_sleep = (ImageView) findViewById(R.id.main_iv_sleep);
    }

    private void setLitenser() {
        imgBtn_Prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                moveNumberToPrevious();
//                play(number);
//                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                sendBroadcastOnCommand(MusicService.COMMAND_PREV);

            }
        });

        imgBtn_PlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                if (player != null && player.isPlaying()) {
//                    pause();
//                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_play);
//                } else {
//                    play(number);
//                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);

                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }
//                }

            }
        });

        imgBtn_Next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                moveNumberToNext();
//                play(number);
//                imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);

            }
        });

        repeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (MusicService.CIRCULATION_MODE) {
                    case 0:MusicService.CIRCULATION_MODE = 1;
                        repeat.setBackgroundResource(R.drawable.sequence_play);
                        break;
                    case 1:MusicService.CIRCULATION_MODE = 2;
                        repeat.setBackgroundResource(R.drawable.listt_play);
                        break;
                    case 2:MusicService.CIRCULATION_MODE = 3;
                        repeat.setBackgroundResource(R.drawable.suffle_play);
                        break;
                    case 3:MusicService.CIRCULATION_MODE = 0;
                        repeat.setBackgroundResource(R.drawable.single_play);
                        break;
                    default:
                        break;
                }
            }
        });
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                number = i ;
                //play(number);
               // imgBtn_PlayOrPause.setBackgroundResource(R.drawable.button_pause);
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status != MusicService.STATUS_STOPPED){
                    time =seekBar.getProgress();
                    //更新文本
                    text_Current.setText(formatTime(time));
                    //发送广播给Musicservice,执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status == MusicService.STATUS_PLAYING) {
                    //发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);

                }


                if(status == MusicService.STATUS_PAUSED){

                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
            }
        });
    }

    private void initmusiclist() {
        String[] media_music_info = new String[]{MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM_ID};
        Cursor musiccursor = this.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                media_music_info, null, null,
                MediaStore.Audio.AudioColumns.TITLE);

        if (musiccursor != null) {

            for (musiccursor.moveToFirst(); !musiccursor.isAfterLast(); musiccursor
                    .moveToNext()) {
                String Title = musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                String Artist = musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                String TotoalTime = musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                String Path = musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA));

                Music music = new Music(Title, Artist, Path, TotoalTime);
//                musicArrayList.add(music);
                MusicList.getMusicarray().add(music);
            }

        }

    }


    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (Music music : MusicList.getMusicarray()) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getmusicName());
            map.put("musicArtist", music.getmusicArtist());
            list_map.add(map);
        }

        String[] from = new String[]{"musicName", "musicArtist"};
        int[] to = {R.id.list_item_title, R.id.list_item_artist};

        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview, from, to);
        list.setAdapter(simpleAdapter);
    }


    private void checkMusicfile() {
        if (MusicList.getMusicarray().isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Prev.setEnabled(false);

            Toast.makeText(getApplicationContext(), "当前没有歌曲文件", Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Prev.setEnabled(true);


        }
    }
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);

        if(sleepmode == MainActivity.ISSLEEP)
            iv_sleep.setVisibility(View.VISIBLE);
        else
            iv_sleep.setVisibility(View.INVISIBLE);
    }


    private void sendBroadcastOnCommand(int command) {

        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        //根据不同命令，封装不同的数据
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;
            case MusicService.COMMAND_PREV:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    private MediaPlayer player = new MediaPlayer();

    private void load(int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicarray().get(number).getmusicPath());
            player.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void play(int number) {
        // ֹͣ停止当前播放
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        player.start();
    }


    private void pause() {
        if (player.isPlaying()) {
            player.pause();
        }
    }

//    private void stop() {
//        player.stop();
//    }
//
//    private void resume() {
//        player.start();
//    }
//
//    private void replay() {
//        player.start();
//    }

    private void moveNumberToNext() {
        if ((number) == MusicList.getMusicarray().size() - 1) {
            Toast.makeText(MainActivity.this, "已经到达列表底端，现在播放第一曲", Toast.LENGTH_SHORT).show();
        } else {
            ++number;
            play(number);
        }
    }


    private void moveNumberToPrevious() {
        if (number == 0) {
            Toast.makeText(MainActivity.this, "已经到达列表顶端，现在播放最后一曲", Toast.LENGTH_SHORT).show();
        } else {
            --number;
            play(number);
        }
    }

    private class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            //获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000L);
                    text_Duration.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    break;
                case MusicService.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    break;
                case MusicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    if (number == MusicList.getMusicarray().size() - 1)
                        sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                    else
                    sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                default:
                    break;
            }
        }
    }

    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        if(minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }

        String secondString;
        if(second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }

        return minuteString + ":" + secondString;
    }

    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(time);
                            //seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }

    private void setTheme(String theme) {
        if ("彩色".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_color);
        } else if ("花朵".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_digit_flower);
        } else if ("群山".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_mountain);
        } else if ("小狗".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_running_dog);
        } else if ("冰雪".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_snow);
        } else if ("女孩".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_music_girl);
        } else if ("朦胧".equals(theme)) {
            this.root_Layout.setBackgroundResource(R.drawable.bg_blur);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_theme:
                new android.app.AlertDialog.Builder(this)
                        .setTitle("请选择主题").
                        setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        Toast.makeText(MainActivity.this,"sss"+which,Toast.LENGTH_SHORT).show();
                                        Log.e("222222",which+"");
                                        PropertyBean property = new PropertyBean(MainActivity.this);
                                        String theme =property.THEMES[which];
//                                        theme= PropertyBean.THEMES[which];
                                        Log.i("1111111",theme);
                                        MainActivity.this.setTheme(theme);
                                        property.setAndSaveTheme(theme);
                                    }
                                }).show();
                break;
            case R.id.menu_about:
                new android.app.AlertDialog.Builder(MainActivity.this)
                        .setTitle("GRacePlayer")
                        .setMessage(R.string.about2)
                        .show();
                break;

            case R.id.menu_sleep:
                showSleepDialog();
                break;

        }

        return super.onOptionsItemSelected(item);
    }

    private void showSleepDialog() {
        //先用getLayoutInflater().inflate方法获取布局，用来初始化一个View类对象
        final View userview = this.getLayoutInflater().inflate(R.layout.dialog, null);
        //通过View类的findViewById方法获取到组件对象
        final TextView tv_minute = (TextView) userview.findViewById(R.id.dialog_listview);
        final Switch switch1 = (Switch)userview.findViewById(R.id.dialog_switch);
        final SeekBar seekbar = (SeekBar)userview.findViewById(R.id.dialog_seekbar);

        tv_minute.setText("睡眠于:"+sleepminute+"分钟");

        if(sleepmode == MainActivity.ISSLEEP)
            switch1.setChecked(true);

        seekbar.setMax(60);
        seekbar.setProgress(sleepminute);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                // TODO Auto-generated method stub
                sleepminute = arg1;
                tv_minute.setText("睡眠于:"+sleepminute+"分钟");

            }
        });

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                // TODO Auto-generated method stub
                sleepmode = arg1;
            }
        });


        //定义定时器任务
        final TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.exit(0);
            }
        };


        final android.app.AlertDialog.Builder dialog = new android.app.AlertDialog.Builder(this);
        dialog.setTitle("选择睡眠时间(0~60分钟)");
        //设置布局
        dialog.setView(userview);
        //设置取消按钮响应事件
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
            }
        });

        //设置重置按钮响应时间
        dialog.setNeutralButton("重置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if(sleepmode == MainActivity.ISSLEEP)
                {
                    timerTask.cancel();
                    timer_sleep.cancel();
                }
                sleepmode = MainActivity.NOTSLEEP;
                sleepminute = 20;
                iv_sleep.setVisibility(View.INVISIBLE);
            }
        });
        //设置确定按钮响应事件
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                if(sleepmode == MainActivity.ISSLEEP)
                {
                    timer_sleep = new Timer();
                    int time =seekbar.getProgress();
                    //启动任务，time*60*1000毫秒后执行
                    timer_sleep.schedule(timerTask, time*60*1000);
                    iv_sleep.setVisibility(View.VISIBLE);
                }
                else
                {
                    //取消任务
                    timerTask.cancel();
                    if(timer_sleep != null) timer_sleep.cancel();
                    arg0.dismiss();
                    iv_sleep.setVisibility(View.INVISIBLE);
                }
            }
        });

    dialog.show();
    }
}